import * as utils from '@/utils/index'
// import * as auth from '@/utils/auth'
export function handleDecode(url = '') {
  /* eslint-disable no-cond-assign */
  url = url || ''
  const reg = /\{\{(.*?)\}\}/g
  const array = []
  let temp = null
  while ((temp = reg.exec(url))) {
    array.push({
      tem: temp[0],
      key: temp[1]
    })
  }

  array.forEach(({ tem, key }) => {
    const value = getValueByKey(key) || ''
    url = url.replace(tem, value)
  })
  return url
}

// window.handleDecode = handleDecode

export function getValueByKey(key) {
  if (!key) {
    return ''
  }
  let value = ''
  if (key === 'jurl') {
    return encodeURIComponent(window.location.href)
  } else {
    const query = utils.param2Obj()
    value = query[key] || ''
  }
  return value
}

export function handelJumpUrl(data) {
  // action 跳转地址
  // method = 跳转方式  POST:表单提及 REDIRECT:地址跳转
  // replace 是否使用replace当前页面 1 是 0 否
  // payload 表单提交参数
  let { action, method } = data
  method = method.toUpperCase()
  action = handleDecode(action)
  if (method === 'REDIRECT') {
    data.replace === '1'
      ? window.location.replace(action)
      : (window.location.href = action)
  } else {
    const payload = data.payload || []
    const currentData = utils.deep(payload)
    for (const key in payload) {
      const value = payload[key]
      if (value === '{{}}') {
        currentData[key] = getValueByKey(key)
      }
    }
    utils.submitForm(action, method, currentData)
  }
}
